package com.mobilesales.android.c2dm.parsers;

import android.content.Context;
import android.util.Log;

import com.mobilesales.android.database.ClientManager;
import com.mobilesales.android.model.clients.Client;
import com.mobilesales.android.model.clients.ClientGroup;
import com.mobilesales.android.services.ClientServiceClient;
import com.mobilesales.android.util.Settings;

public class ClientMessageParser extends MessageParserBase {

	private ClientManager manager;
	private ClientServiceClient service;

	public ClientMessageParser(Context context) {
		super(context);
	}
	
	public ClientMessageParser() {
		super();
	}

	@Override
	public boolean parseMessage(String method, String arg) {
		manager = new ClientManager(getContext());
		service = new ClientServiceClient(Settings.ClientService());
		try {
			this.invokeMethod(ClientMessageParser.class, method,arg);
			return true;
		}
		catch(Exception ex) {
			Log.e("MessageParser", ex.getMessage(), ex);
			return false;
		}
		finally {
			manager.Close();
		}
	}

	public void GetClient(Integer id) throws Exception {
		Client client = service.getClient(id);
		if (client!=null) {
			if (!manager.StoreClient(client))
				throw new Exception("Could not store client");
		}
		else {
			throw new Exception("Retrieved client is null");
		}
	}
	
	public void DeleteClient(Integer id) throws Exception {
		if (!manager.RemoveClient(id))
			throw new Exception("Could not delete client");		
	}
	
	public void GetClientGroup(Integer id) throws Exception {
		ClientGroup clientGroup = service.getClientGroup(id);
		if (clientGroup!=null) {
			if (!manager.StoreClientGroup(clientGroup))
				throw new Exception("Could not store client group");
		}
		else {
			throw new Exception("Retrieved client group is null");
		}
	}
	
	public void DeleteClientGroup(Integer id) throws Exception {
		if (!manager.RemoveClientGroup(id))
			throw new Exception("Could not delete client");
	}
	
}
